/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseProsecutionIdDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseReconsiderPageQueryRequest;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseReconsiderRegisterSaveDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseReconsiderResultSaveDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseReconsiderMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseReconsider;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseHandlePersonAdjustInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseReconsiderService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseProsecutionFileVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseReconsiderRegisterVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseReconsiderResultVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseReconsiderVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 案件复议表 case_reconsider 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年12月08日
 */
@Service
public class CaseReconsiderServiceImpl extends MyBatisServiceSupport implements ICaseReconsiderService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseReconsiderServiceImpl.class);

    @Resource
    private CaseReconsiderMapper caseReconsiderMapper;

    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;

    @Autowired
    private ICaseHandlePersonAdjustInfoService caseHandlePersonAdjustInfoService;

    /**
     * 分页获取案件复议列表
     *
     * @param request 请求对象
     * @return 复议列表
     * @author lilihao
     * @date 2022/12/8 0:45
     */
    @Override
    public PageResponse<CaseReconsiderVo> getPageList(CaseReconsiderPageQueryRequest request) {
        request.setCaseOrgCode(UserUtil.getUserInfo().getOrgCode());
        PageHelper.startPage(request.getPageNum(), request.getLength());
        List<CaseReconsiderVo> list = caseReconsiderMapper.getPageList(request);
        list.forEach(a -> {
            a.setCaseStatusName(CaseStatusEnum.getValueByCode(a.getCaseStatus()));
            //查询承办人
            String caseId = a.getCaseId();
            //1.循环设置处理人员
            Example example = new Example(CaseHandlePersonRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1);
            example.orderBy("handlePersonType").asc();
            List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.selectByExample(example);
            String handPersonName = handlePersonRecords.stream().map(p -> p.getHandlePersonName()).collect(Collectors.joining(","));
            a.setHandleName(handPersonName);
            String partyName = caseHandlePersonAdjustInfoService.getPartyName(a.getCaseId());
            a.setPartyName(partyName);
        });
        return new PageResponse<>(list);
    }

    /**
     * 获取案件复议详情
     *
     * @param idDto 请求对象
     * @return 复议详情列表
     * @author lilihao
     * @date 2022/12/5 16:11
     */
    @Override
    public Dict getDetail(CaseProsecutionIdDto idDto) {
        Dict dict = Dict.create();
        CaseReconsider caseReconsider = caseReconsiderMapper.selectByPrimaryKey(idDto.getId());
        if (ObjectUtil.isNotNull(caseReconsider)) {
            CaseReconsiderRegisterVo caseReconsiderRegisterVo = BeanUtil.toBean(caseReconsider, CaseReconsiderRegisterVo.class);
            if (StrUtil.isNotBlank(caseReconsider.getRegisterFile())) {
                JSONArray objects = JSONUtil.parseArray(caseReconsider.getRegisterFile());
                List<CaseProsecutionFileVo> fileList = JSONUtil.toList(objects, CaseProsecutionFileVo.class);
                caseReconsiderRegisterVo.setFileList(fileList);
            }
            dict.put("1", caseReconsiderRegisterVo);
            if (StrUtil.isNotBlank(caseReconsider.getHandleResult())) {
                CaseReconsiderResultVo reconsiderResultVo = BeanUtil.toBean(caseReconsider, CaseReconsiderResultVo.class);
                if (StrUtil.isNotBlank(caseReconsider.getResultFile())) {
                    JSONArray objects = JSONUtil.parseArray(caseReconsider.getResultFile());
                    List<CaseProsecutionFileVo> fileList = JSONUtil.toList(objects, CaseProsecutionFileVo.class);
                    reconsiderResultVo.setFileList(fileList);
                }
                dict.put("2", reconsiderResultVo);
            }
        }
        return dict;
    }

    /**
     * 保存复议登记信息
     *
     * @param registerSaveDto 复议登记保存对象
     * @return
     * @author lilihao
     * @date 2022/12/8 14:56
     */
    @Override
    public int saveRegisterInfo(CaseReconsiderRegisterSaveDto registerSaveDto) {
        //1.判断登记复议是否已存在
        Example example = new Example(CaseReconsider.class);
        example.createCriteria()
                .andEqualTo("caseId", registerSaveDto.getCaseId())
                .andNotEqualTo("id", StrUtil.isNotBlank(registerSaveDto.getId()) ? registerSaveDto.getId() : "")
                .andEqualTo("isDeleted", "0")
                .andEqualTo("documentNumber", registerSaveDto.getDocumentNumber());
        List<CaseReconsider> list = caseReconsiderMapper.selectByExample(example);
        if (CollectionUtil.isNotEmpty(list)) {
            throw new BusinessException("该案件该文书已登记复议，请勿重复操作");
        }

        CaseReconsider caseReconsider = BeanUtil.toBean(registerSaveDto, CaseReconsider.class);
        UserDTO userInfo = UserUtil.getUserInfo();
        //2.处理附件
        if (CollectionUtil.isNotEmpty(registerSaveDto.getFileList())) {
            caseReconsider.setRegisterFile(JSONUtil.toJsonStr(registerSaveDto.getFileList()));
        } else {
            caseReconsider.setRegisterFile("");
        }
        //3.新增/修改复议登记信息
        if (StrUtil.isBlank(registerSaveDto.getId())) {
            caseReconsider.setId(BaseUtil.createUid());
            caseReconsider.setCreateTime(new Date());
            caseReconsider.setCreateUserId(String.valueOf(userInfo.getUserId()));
            caseReconsider.setIsDeleted(Constant.STRING_0);
            caseReconsiderMapper.insert(caseReconsider);
        } else {
            caseReconsider.setUpdateTime(new Date());
            caseReconsider.setUpdateUserId(String.valueOf(userInfo.getUserId()));
            caseReconsiderMapper.updateByPrimaryKeySelective(caseReconsider);
        }
        return 1;
    }

    /**
     * 获取复议登记信息
     *
     * @param idDto 请求对象
     * @return 复议登记信息
     * @author lilihao
     * @date 2022/12/8 16:16
     */
    @Override
    public CaseReconsiderRegisterVo getRegisterInfo(CaseProsecutionIdDto idDto) {
        CaseReconsider caseReconsider = caseReconsiderMapper.selectByPrimaryKey(idDto.getId());
        if (ObjectUtil.isNull(caseReconsider)) {
            throw new BusinessException("案件复议不存在");
        }
        CaseReconsiderRegisterVo reconsiderRegisterVo = BeanUtil.toBean(caseReconsider, CaseReconsiderRegisterVo.class);
        if (StrUtil.isNotBlank(caseReconsider.getRegisterFile())) {
            JSONArray objects = JSONUtil.parseArray(caseReconsider.getRegisterFile());
            List<CaseProsecutionFileVo> fileList = JSONUtil.toList(objects, CaseProsecutionFileVo.class);
            reconsiderRegisterVo.setFileList(fileList);
        }
        return reconsiderRegisterVo;
    }

    /**
     * 删除复议信息
     *
     * @param idDto 请求id
     * @author lilihao
     * @date 2022/12/8 23:02
     */
    @Override
    public int delInfo(CaseProsecutionIdDto idDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        CaseReconsider caseReconsider = CaseReconsider.builder().id(idDto.getId())
                .updateTime(new Date())
                .updateUserId(String.valueOf(userInfo.getUserId()))
                .isDeleted(Constant.STRING_1).build();
        return caseReconsiderMapper.updateByPrimaryKeySelective(caseReconsider);
    }

    /**
     * 保存复议结果信息
     *
     * @param saveDto 保存信息
     * @return 状态：1：存储成功，
     * @author lilihao
     * @date 2022/12/5 4:01
     */
    @Override
    public int saveResultInfo(CaseReconsiderResultSaveDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        CaseReconsider caseReconsider = BeanUtil.toBean(saveDto, CaseReconsider.class);
        caseReconsider.setUpdateTime(new Date());
        caseReconsider.setUpdateUserId(String.valueOf(userInfo.getUserId()));
        caseReconsider.setReconsiderState(Constant.STRING_2);
        //1.处理附件
        if (CollectionUtil.isNotEmpty(saveDto.getFileList())) {
            caseReconsider.setResultFile(JSONUtil.toJsonStr(saveDto.getFileList()));
        } else {
            caseReconsider.setResultFile("");
        }
        return caseReconsiderMapper.updateByPrimaryKeySelective(caseReconsider);
    }
}